<?php


namespace App\Dao;


use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\CertificationIdcard;
use App\Utils\IDCard;

class CertificationIdcardDao extends AbstractDao
{
    public function where(array $where): \Hyperf\Database\Model\Builder
    {
        $query = CertificationIdcard::query();
        foreach ($where as $key => $value) {
            $query->where($key, $value);
        }
        return $query;
    }

    /**
     * @param array $data
     * @return CertificationIdcard
     */
    public function create(array $data):CertificationIdcard
    {
        $certificationIdcard = $this->first(
            [
                'idcard' => $data['idcard'],
                'name' => $data['name']
            ]
        );
        if(\env('APP_ENV') == 'prod' ){
            try{
                IDCard::check($data['idcard'], $data['name']);
            }catch (\Hyperf\Server\Exception\RuntimeException $exception){
                throw new BusinessException(ErrorCode::CERTIFICATION_SYSTEM_ERROR);
            }
        }
        if (!$certificationIdcard) {
            $certificationIdcard = new CertificationIdcard();
            $certificationIdcard->idcard = $data['idcard'];
            $certificationIdcard->name = $data['name'];
            $certificationIdcard->save();
        }
        return $certificationIdcard;
    }
}